using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Toenda.Rails.System;
using Toenda.Rails.Data;
using Toenda.Rails.DataContainer;
using Toenda.TFL.Base;

public partial class Controls_Main_ctrl_images : System.Web.UI.UserControl {
	private AccountProvider ap = new AccountProvider();
	private ImageProvider ip = new ImageProvider();
	private Tools t = new Tools();
	private ServerPath serverpath = new ServerPath();
	private Validator vali = new Validator();
	private int page;
	private int currentpage;
	private long amount;
	private string tag = "";
	private int _images_per_page = 16;

	/// <summary>
	/// Page_Load
	/// </summary>
	/// <param name="sender"></param>
	/// <param name="e"></param>
	protected void Page_Load(object sender, EventArgs e) {
		if(Request.QueryString.Get("User") != null) {
			if(ap.CheckUsernameExist(Request.QueryString.Get("User").ToString())) {
				int line = 0;
				int comments = 0;
				long views = 0;
				bool letView = false;
				bool isLoggedIn = false;
				bool isOwner = false;
				string imgtitle = "";

				Account tmp = new Account();

				List<ImageItem> items = new List<ImageItem>();

				HtmlTableRow row = null;
				HtmlTableRow row2 = null;

				if(Session.Count > 0 && ap.CheckSessionExist(Session["Zappr"].ToString())) {
					tmp = ap.GetAccountBySession(Session["Zappr"].ToString());
					isLoggedIn = true;
				}

				// tag
				if(Request.QueryString.Get("tag") == null) {
					tag = "";
				}
				else {
					tag = Request.QueryString.Get("tag").ToString();
				}

				Account acc = ap.GetAccountByUsername(Request.QueryString.Get("user").ToString());

				// imagelist layout
				switch(acc.AccountSettings.ImageListLayout) {
					case ImageListLayout.SmallImagesAndSets:
						this._images_per_page = 16;
						break;

					case ImageListLayout.MediumImagesAndSets:
						this._images_per_page = 5;
						break;

					default:
						this._images_per_page = 16;
						break;
				}

				if(!string.IsNullOrEmpty(tmp.ID)) {
					if(acc.ID == tmp.ID) {
						isOwner = true;
					}
				}

				// pages
				if(Request.QueryString.Get("page") == null) {
					page = 0;
					currentpage = 1;
				}
				else {
					page = Convert.ToInt32(Request.QueryString.Get("page").ToString());
					currentpage = page;
					page = t.ConvertPageToStartValue(page, this._images_per_page);
				}

				// get images
				if(tag == "") {
					items = ip.GetImageList(
						acc.ID, 
						page, 
						page + this._images_per_page, 
						this._images_per_page, 
						true,
						isOwner
					);
					amount = ip.GetImageAmount(acc.ID);
				}
				else {
					items = ip.GetImageListByTag(
						tag, 
						-1, 
						page, 
						page + this._images_per_page, 
						acc.ID, 
						this._images_per_page
					);
					amount = ip.GetImageAmountByTag(acc.ID, tag, 0);
				}

				// re-generate badge
				if(isLoggedIn && tmp != null && tmp.ID != "") {
					BadgeSettings bs = ip.GetBadgeSetting(tmp.ID);
					string code = "";

					if(bs != null && bs.ID != "") {
						code = ip.GenerateZapprBadge(
							bs,
							serverpath.Path + @"/Badges/",
							serverpath.Path + @"/Images/"
						);
					}
				}

				// list images
				foreach(ImageItem item in items) {
					if(line == 0) {
						row = new HtmlTableRow();
						row2 = new HtmlTableRow();
					}

					// check privacy
					//if(isLoggedIn && item.UserID == tmp.ID) {
					//    if(item.Access > 0) {
					//        // this time: only the user itself
					//        // next time: friends and family
					//        if(item.UserID == acc.ID)
					//            letView = true;
					//    }
					//    else
					//        letView = true;
					//}
					//else {
					//    if(item.Access == 0)
					//        letView = true;
					//}

					letView = true;

					if(letView) {
						comments = ip.GetImageCommentAmount(item.ID);
						views = ip.GetImageViewAmount(item.ID);

						/*
						 * title
						 */

						imgtitle = item.Name;

						// imagelist layout
						if(acc.AccountSettings.ImageListLayout == ImageListLayout.SmallImagesAndSets) {
							if(imgtitle.Length > 18) {
								if(imgtitle.IndexOf(' ') == -1 || imgtitle.IndexOf(' ') > 17) {
									imgtitle = item.Name.Substring(0, 16) + "...";
								}
							}
						}
						else if(acc.AccountSettings.ImageListLayout == ImageListLayout.MediumImagesAndSets) {
							if(imgtitle.Length > 40) {
								if(imgtitle.IndexOf(' ') == -1 || imgtitle.IndexOf(' ') > 39) {
									imgtitle = item.Name.Substring(0, 38) + "...";
								}
							}
						}

						HtmlTableCell celltitle = new HtmlTableCell();
						celltitle.VAlign = "top";
						celltitle.Width = "300";
						celltitle.Style.Add("width", "300px");

						// text
						Label title = new Label();
						title.CssClass = "listTitle";
						title.Text = imgtitle;
						title.Text += "<br />";

						celltitle.Controls.Add(title);

						row.Cells.Add(celltitle);
						imageTable.Rows.Add(row);

						/*
						 * image
						 */

						HtmlTableCell cell = new HtmlTableCell();
						cell.VAlign = "top";
						cell.Width = "300";
						cell.Style.Add("width", "300px");

						// image
						HyperLink link;

						// imagelist layout
						if(acc.AccountSettings.ImageListLayout == ImageListLayout.SmallImagesAndSets) {
							link = new HyperLink();
							link.ImageUrl = "../../Images/" + item.Image240;
							link.CssClass = "listTitle";
							//link.NavigateUrl = "~/default.aspx?item=" + item.ImageID.ToString();
							link.NavigateUrl = "~/photo/" + item.ImageID.ToString() + "/default.aspx";
							link.Text = item.Name;

							cell.Controls.Add(link);
						}
						else if(acc.AccountSettings.ImageListLayout == ImageListLayout.MediumImagesAndSets) {
							link = new HyperLink();
							link.ImageUrl = "../../Images/" + item.Image500;
							link.CssClass = "listTitle";
							//link.NavigateUrl = "~/default.aspx?item=" + item.ImageID.ToString();
							link.NavigateUrl = "~/photo/" + item.ImageID.ToString() + "/default.aspx";
							link.Text = item.Name;

							cell.Controls.Add(link);
						}

						// newline
						Literal lit0 = new Literal();
						lit0.Text = "<br />";

						cell.Controls.Add(lit0);

						// text
						Label text = new Label();
						text.CssClass = "listText";
						text.Text = item.Description;

						cell.Controls.Add(text);

						// newline
						Literal lit1 = new Literal();
						lit1.Text = "<div style=\"height: 5px; display: block;\"></div>";

						cell.Controls.Add(lit1);

						/*
						 * footer
						 */

						// image footer 1
						Label footer1 = new Label();
						footer1.CssClass = "listFooter";

						switch(item.Access) {
							case 0:
								footer1.Text = "&copy; " + GetLocalResourceObject("PhotoIsPublic").ToString() + " ";
								break;

							case 1:
								footer1.Text = "&copy; " + GetLocalResourceObject("PhotoIsPrivate").ToString() + " ";
								break;

							default:
								footer1.Text = "&copy; " + GetLocalResourceObject("PhotoIsPublic").ToString() + " ";
								break;
						}

						cell.Controls.Add(footer1);

						// image footer change link
						if(isLoggedIn && item.UserID == tmp.ID) {
							LinkButton change = new LinkButton();
							change.CssClass = "listFooter";
							change.Text = GetLocalResourceObject("Change").ToString();
							//change.Command += new CommandEventHandler(btnChange_Click);
							//change.CommandName = "btnChange_Click";
							//change.CommandArgument = item.ImageID.ToString();

							change.PostBackUrl = "~/default.aspx?id=_edit&photo=";
							change.PostBackUrl += item.ImageID.ToString();

							cell.Controls.Add(change);
						}

						// footer 1.5
						Label footer15 = new Label();
						footer15.CssClass = "listFooter";
						footer15.Text += "<br />";
						footer15.Text += GetLocalResourceObject("UploadedOn").ToString() + " ";
						footer15.Text += item.UploadDate.ToShortDateString();
						// Sep 10, 2006
						if(isLoggedIn && item.UserID == tmp.ID) {
							footer15.Text += " | ";
						}

						cell.Controls.Add(footer15);

						// image footer delete link
						if(isLoggedIn && item.UserID == tmp.ID) {
							LinkButton del = new LinkButton();
							del.CssClass = "listFooter";
							del.OnClientClick = "javascript:chk=confirm('"
								+ GetLocalResourceObject("DeleteThis").ToString()
								+ "');return chk;";
							del.Text = GetLocalResourceObject("Delete").ToString();
							//del.Command += new CommandEventHandler(btnDelete_Click);
							//del.CommandName = "btnDelete_Click";
							//del.CommandArgument = item.ImageID.ToString();

							del.PostBackUrl = "~/default.aspx?id=_delete&photo=";
							del.PostBackUrl += item.ImageID.ToString();

							cell.Controls.Add(del);
						}

						// image footer 2
						if(isLoggedIn && item.UserID == tmp.ID) {
							Label footer2 = new Label();
							footer2.CssClass = "listFooter";

							footer2.Text += "<br />";
							footer2.Text += views.ToString();
							footer2.Text += " " + GetLocalResourceObject("Views").ToString() + " / ";

							cell.Controls.Add(footer2);
						}
						else {
							Label lit_1 = new Label();
							lit_1.CssClass = "listFooter";
							lit_1.Text += " / ";

							cell.Controls.Add(lit_1);
						}

						// title
						HyperLink footerLink = new HyperLink();
						footerLink.CssClass = "listFooter";
						//footerLink.NavigateUrl = "~/default.aspx?item=" + item.ImageID.ToString();
						footerLink.NavigateUrl = "~/photo/"  + item.ImageID.ToString() + "/default.aspx";
						footerLink.Text = comments.ToString() + " "
							+ (comments == 1 ? GetLocalResourceObject("Comment").ToString() : GetLocalResourceObject("Comments").ToString());

						cell.Controls.Add(footerLink);

						// box
						Literal box2 = new Literal();
						box2.Text = "</div><br /><br />";

						cell.Controls.Add(box2);

						/*
						 * next
						 */

						row2.Cells.Add(cell);
						imageTable.Rows.Add(row2);

						letView = false;
						line++;
					}

					// imagelist layout
					if(acc.AccountSettings.ImageListLayout == ImageListLayout.SmallImagesAndSets) {
						if(line == 2) {
							row = null;
							row2 = null;

							line = 0;
						}
					}
					else if(acc.AccountSettings.ImageListLayout == ImageListLayout.MediumImagesAndSets) {
						if(line == 1) {
							row = null;
							row2 = null;

							line = 0;
						}
					}
				}

				if(amount > this._images_per_page || page > 0) {
					this.DisplayPageList(acc.Username, Convert.ToInt32(amount));
				}
			}
		}
	}

	/// <summary>
	/// Display the pages on the footer
	/// </summary>
	/// <param name="amount"></param>
	private void DisplayPageList(string username, int amount) {
		double tmp = System.Math.Round(
			(Convert.ToDouble(amount) / this._images_per_page), 
			0, 
			MidpointRounding.AwayFromZero
		);
		long pages = Convert.ToInt64(tmp);
		//long pages = (Convert.ToInt64(amount) / 16) + 1;
		int counter = 0;
		double chk = 0;

		// pages
		HyperLink link = null;

		if(pages > 1) {
			plcFooter.Controls.Add(new LiteralControl("<br />"));

			if(currentpage != 1) {
				link = null;
				link = new HyperLink();
				link.CssClass = "pageStep";
				link.NavigateUrl = "~/default.aspx?id=images";
				link.NavigateUrl += "&user=" + username;
				link.NavigateUrl += "&page=" + (currentpage - 1).ToString();
				link.Text = GetLocalResourceObject("Previous").ToString();

				plcFooter.Controls.Add(link);
			}

			for(int i = 1; i <= pages; i++) {
				link = new HyperLink();

				if(i == currentpage) {
					link.CssClass = "pageCurrentStep";
				}
				else {
					link.CssClass = "pageStep";
				}

				link.NavigateUrl = "~/default.aspx?id=images";
				link.NavigateUrl += "&user=" + username;
				
				if(tag != "") {
					link.NavigateUrl += "&tag=" + tag;
				}

				link.NavigateUrl += "&page=" + i.ToString();
				link.Text = i.ToString();

				// aktiver link ist "page"

				plcFooter.Controls.Add(link);

				// check
				chk = counter;
				chk = Convert.ToDouble(counter) / 13;
				if(vali.IsNaturalNumber(chk) && counter > 2) {
					plcFooter.Controls.Add(new LiteralControl("<br /><br />"));
				}
				else {
					plcFooter.Controls.Add(new LiteralControl("&nbsp;"));
				}

				link = null;
				counter++;
			}

			if(currentpage < counter) {
				link = null;
				link = new HyperLink();
				link.CssClass = "pageStep";
				link.NavigateUrl = "~/default.aspx?id=images";
				link.NavigateUrl += "&user=" + username;
				link.NavigateUrl += "&page=" + (currentpage + 1).ToString();
				link.Text = GetLocalResourceObject("Next").ToString();

				plcFooter.Controls.Add(link);
			}
		}
	}
}
